package bailiny.decoder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;

/**
 * @author Yang Xu
 * @date 2020/5/6 17:11
 * @description:
 */
public class TimeClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int counter;

    private byte[] req;

    public TimeClientHandler() {
        req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes();
    }

    /**
     * 客户端连接后不断向服务器发送消息，循环发送100条消息，每发送一次就刷新一次，保证每条消息都写入Channel中。
     * 期望服务器可以接收到100次消息，但实际只收到2次，发生了粘包
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf message = null;
        for (int i = 0; i < 100; i++) {
            message = Unpooled.buffer(req.length);
            message.writeBytes(req);
            ctx.writeAndFlush(message);
        }
    }



    /**
     * 客户端收到服务端消息
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] req = new byte[msg.readableBytes()];
        msg.readBytes(req);
        String body = new String(req, "UTF-8");
        System.out.println(new Date() + ": 客户端读到数据 -> " + body + "; the counter is" + ++counter);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
